//  Copyright (c) 2010, Mark Sivill, Sales Engineering, Salesforce.com Inc.
//  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//  Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 
//  Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//  Neither the name of the salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
//  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
//  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
//  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
//  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// History
//
// Version  Date            Author          Comments
// 1.0      21-10-2010      Mark Sivill     Initial version
//
//
// Create associated stock audit items or attachments for visit activity
//
// NOTE code not bulkified
//
trigger OutletVisitActivityAfterInsert on Outlet_Visit_Activity__c (after insert) {

	//
	// check to see if attachments or stock audit items need to be created for visit activity
	// also pull back some stock info for later processing
	//
	// combined with product range query
	//Select o.Outlet_Visits_LU__r.Account__c, o.Outlet_Visits_LU__c, o.Objective_Activity__r.Objective__c, o.Objective_Activity__r.Objective__r.Product_Range__c, o.Objective_Activity__c From Outlet_Visit_Activity__c o
	//WHERE o.Objective_Activity__r.Objective__r.Product_Range__c != null
	//
	//
	// given time could also combine attachments SOQL logic in here as well
	//
/*	List<Outlet_Visit_Activity__c> visitActivities  = [SELECT
															o.id,
															o.Objective_Activity__c,
															o.Objective_Activity__r.Product_Range_Related__c,
															o.Objective_Activity__r.Attachment_Count__c,
															o.Outlet_Visits_LU__r.Account__c
														FROM
															Outlet_Visit_Activity__c o
														WHERE o.id IN :System.Trigger.new
														AND ( o.Objective_Activity__r.Attachment_Count__c > 0
															OR o.Objective_Activity__r.Product_Range_Related__c = true )
														];
*/

	List<Outlet_Visit_Activity__c> visitActivities  = [SELECT
															o.id,
															o.Objective_Activity__c,
															o.Objective_Activity__r.Attachment_Count__c,
															o.Objective_Activity__r.Product_Range_Related__c,
															o.Objective_Activity__r.Objective__c,
															o.Objective_Activity__r.Objective__r.Product_Range__c,
															o.Outlet_Visits_LU__c,
															o.Outlet_Visits_LU__r.Account__c
														FROM
															Outlet_Visit_Activity__c o
														WHERE o.id IN :System.Trigger.new
														AND ( o.Objective_Activity__r.Attachment_Count__c > 0
																OR
																( o.Objective_Activity__r.Objective__r.Product_Range__c != null 
																	AND
															 		o.Objective_Activity__r.Product_Range_Related__c = true
															 	)
															 )
														];

	List<Outlet_Visit_Activity__c> visitActivityAttachments = new List<Outlet_Visit_Activity__c>();
	List<Outlet_Visit_Activity__c> visitActivityStockAudits = new List<Outlet_Visit_Activity__c>();

	for (Outlet_Visit_Activity__c va:visitActivities)
	{
		// need attachments?
		if (va.Objective_Activity__r.Attachment_Count__c > 0)
		{
			visitActivityAttachments.add(va);
		}
		
		// need stock audit?
		if (va.Objective_Activity__r.Product_Range_Related__c == true)
		{
			visitActivityStockAudits.add(va);	
		}
	}

System.Debug('*********** OutletVisitActivityAfterInsert visitActivityAttachments ' + visitActivityAttachments);	
System.Debug('*********** OutletVisitActivityAfterInsert visitActivityStockAudits ' + visitActivityStockAudits);	

	// process attachments if any found
	if(visitActivityAttachments.size()>0)
	{
	
		Set<Id> visitActivityAttachmentsID = new Set<Id>();
		for (Outlet_Visit_Activity__c i:visitActivityAttachments)
		{
			visitActivityAttachmentsID.add(i.Objective_Activity__c);			
		}
				
		List<Objective_Activity__c> objectiveActivities = [SELECT
																o.Id,
																(SELECT
																		a.Name,
																		a.Filename__c,
																		a.Comments__c
																	FROM
																		Objective_Activity_Attachments__r a )
															FROM Objective_Activity__c o
															WHERE o.Id IN :visitActivityAttachmentsID
															];

		// new list to create
		List<Outlet_Activity_Attachment__c> activityAttachments = new List<Outlet_Activity_Attachment__c>();

		for( Objective_Activity__c oa:objectiveActivities)
		{
			for(Objective_Activity_Attachment__c oaa:oa.Objective_Activity_Attachments__r)
			{
				// not efficient but need to find all visit activities for objective
				for ( Outlet_Visit_Activity__c va:visitActivityAttachments)
				{	
					if (va.Objective_Activity__c == oa.id)
					{
						activityAttachments.add( new Outlet_Activity_Attachment__c (Outlet_Visit_Activities__c = va.id,
																			 Name = oaa.Name,
																			 Filename__c = oaa.Filename__c,
																			 Comments__c = oaa.Comments__c
																		) );								
					}
				}
			}
		}
		
		if(activityAttachments.size()>0)
		{
			insert activityAttachments;
		}					
		
	}

	// process stock audit if found
	if(visitActivityStockAudits.size()>0)
	{

		// work out unique accounts
		Set<Id> visitActivityAccountIDs = new Set<Id>();
		for (Outlet_Visit_Activity__c i:visitActivityStockAudits)
		{
			if ( i.Outlet_Visits_LU__r.Account__c != null)
			{
				visitActivityAccountIDs.add(i.Outlet_Visits_LU__r.Account__c);
			}			
		}

		// work out unique product ranges
		Set<Id> visitActivityProductRangeIDs = new Set<Id>();
		for (Outlet_Visit_Activity__c i:visitActivityStockAudits)
		{
			if ( i.Objective_Activity__r.Objective__r.Product_Range__c != null)
			{
				visitActivityProductRangeIDs.add(i.Objective_Activity__r.Objective__r.Product_Range__c);
			}			
		}

		// for each account and product range combination pull back records for outlet stock
		List<Outlet_Stock__c> outletStocks = [SELECT
													o.Recommendation__c,
													o.Product__r.Product_Range__c,
													o.Product__c,
													o.Product_Range_ID__c,
													o.Account__c
												FROM
													Outlet_Stock__c o
												WHERE
													o.Account__c IN :visitActivityAccountIDs
												AND
													o.Product__r.Product_Range__c IN :visitActivityProductRangeIDs
											];

System.Debug('*********** OutletVisitActivityAfterInsert outletStocks ' + outletStocks);	

		//
		// not effecient but loop through records then match product range and account combination then
		// ceate record in visit stock item
		//
		List<Visit_Stock_Audit_Item__c> visitStockAudits = new List<Visit_Stock_Audit_Item__c>();
		
		for (Outlet_Visit_Activity__c i:visitActivityStockAudits)
		{

System.Debug('*********** OutletVisitActivityAfterInsert in loop visitActivityStockAudits ' + i);	

			for (Outlet_Stock__c j:outletStocks)
			{
System.Debug('*********** OutletVisitActivityAfterInsert in loop outletStock ' + j);	

				if 	(
						( i.Outlet_Visits_LU__r.Account__c != null ) && ( i.Outlet_Visits_LU__r.Account__c == j.Account__c ) 
						&&
						( i.Objective_Activity__r.Objective__r.Product_Range__c != null ) && ( i.Objective_Activity__r.Objective__r.Product_Range__c == j.Product__r.Product_Range__c )
					)
				{
					visitStockAudits.add( new Visit_Stock_Audit_Item__c ( Outlet_Visit_Activity__c = i.id,
																			Outlet_Stock__c = j.Id,
																			Product_Range__c = i.Objective_Activity__r.Objective__r.Product_Range__c
																	)
											);
				}
			}
		}

		if(visitStockAudits.size()>0)
		{
			insert visitStockAudits;
		}					
	}
}